import { useEffect, useRef, useState } from "react";

interface UseCollapsibleContentOptions {
  maxLines?: number;
  content: string;
}

export function useCollapsibleContent({
  maxLines = 20,
  content,
}: UseCollapsibleContentOptions) {
  const [isExpanded, setIsExpanded] = useState(false);
  const [shouldShowToggle, setShouldShowToggle] = useState(false);
  const contentRef = useRef<HTMLDivElement>(null);
  const contentLengthRef = useRef(content.length);

  // 检测内容是否需要折叠
  useEffect(() => {
    // 检查内容长度变化
    const hasContentChanged = content.length !== contentLengthRef.current;
    if (hasContentChanged) {
      contentLengthRef.current = content.length;
    }

    const checkLines = () => {
      if (contentRef.current) {
        const lineHeight = parseInt(
          window.getComputedStyle(contentRef.current).lineHeight,
          10,
        );
        const actualHeight = contentRef.current.scrollHeight;
        const lines = Math.ceil(actualHeight / lineHeight);

        // 更新折叠状态
        const needsToggle = lines > maxLines;
        setShouldShowToggle(needsToggle);

        // 如果内容变短了，自动重置展开状态
        if (!needsToggle) {
          setIsExpanded(false);
        }
      }
    };

    const rafId = requestAnimationFrame(checkLines);
    return () => cancelAnimationFrame(rafId);
  }); // 每次渲染时都检查

  // 处理展开/收起
  const handleToggle = (event: React.MouseEvent<HTMLButtonElement>) => {
    if (isExpanded) {
      // 收起时记录按钮位置
      const button = event.currentTarget;
      const buttonRect = button.getBoundingClientRect();
      const scrollContainer = document.querySelector(
        '[class*="overflow-y-auto"]',
      ) as HTMLElement;

      if (scrollContainer && buttonRect) {
        // 只在按钮不在顶部时才调整滚动
        if (buttonRect.top > 100) {
          // 避免在顶部时调整
          const scrollBefore = scrollContainer.scrollTop;

          setIsExpanded(false);

          requestAnimationFrame(() => {
            const newButtonRect = button.getBoundingClientRect();
            if (newButtonRect) {
              const diff = newButtonRect.top - buttonRect.top;
              if (Math.abs(diff) > 50) {
                scrollContainer.scrollTop = scrollBefore + diff;
              }
            }
          });
        } else {
          setIsExpanded(false);
        }
      } else {
        setIsExpanded(false);
      }
    } else {
      setIsExpanded(true);
    }
  };

  // 内容样式
  const contentStyle = {
    maxHeight: !isExpanded && shouldShowToggle ? `${maxLines * 1.5}em` : "none",
    overflow: !isExpanded && shouldShowToggle ? "hidden" : "visible",
    position: "relative" as const,
  };

  return {
    isExpanded,
    shouldShowToggle,
    contentRef,
    handleToggle,
    contentStyle,
    maxLines,
  };
}
